package com.chy.blog_server.modular.map.export;

import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：导出excel动态列宽处理器
 * 作者：chenhuiyan
 * 时间：2025/03/22 22:07
 */
public class DynamicColumnWidthHandler implements CellWriteHandler {

    // 自定义列宽配置（key=列名，value=字符数）
    private final Map<String, Integer> customWidthMap;

    public DynamicColumnWidthHandler(Map<String, Integer> customWidthMap) {
        this.customWidthMap = customWidthMap;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) { // 关键：使用新的Context参数
        // 仅处理表头行
        if (context.getHead() != null && context.getRowIndex() == 0) {
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            Cell cell = context.getCell();
            String headerName = cell.getStringCellValue();

            // 计算列宽
            int columnWidth = customWidthMap.getOrDefault(headerName,
                    calculateAutoWidth(headerName));

            // 设置列宽（单位：字符数×256）
            sheet.setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
        }
    }

    // 自动计算列宽（优化版）
    private int calculateAutoWidth(String text) {
        int chineseCount = text.replaceAll("[^\\u4e00-\\u9fa5]", "").length();
        int otherCount = text.length() - chineseCount;
        return (int) Math.ceil(chineseCount * 2 + otherCount * 1.2) + 2;
    }

}
